package miage.rest.mail;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

/**
 * Fabrique d'email
 * @author Schwartz Michaël
 */
public class MailFactory {
	private final String smtpHost;
	private final String smtpUser;
	private final String smtpPassword;

	private String smtpFromAddress;
	private String smtpFromName;
	

	public MailFactory(	String smtpHost,
						String smtpUser,
						String smtpPassword,
						String smtpFromAddress,
						String smtpFromName) {
		
		this.smtpFromAddress = smtpFromAddress;
		this.smtpFromName = smtpFromName;
		this.smtpHost = smtpHost;
		this.smtpUser = smtpUser;
		this.smtpPassword = smtpPassword;
		
	}

	/**
	 * Créer un nouveau mail du type donnée
	 * @param <T>
	 * @param emailType
	 * @return
	 * @throws EmailException
	 */
	public <T extends Email> Email create(Class<T> emailType)
			throws EmailException, InstantiationException, IllegalAccessException {
		
		Email email;
		email = emailType.newInstance();
		configureEmail(email);
		
		return email;
	}

	/**
	 * Creer un nouveau mail de type SimpleEmail
	 * @return
	 * @throws EmailException
	 */
	public Email create() throws EmailException {
		Email email = new SimpleEmail();
		configureEmail(email);
		return email;
	}

	private void configureEmail(Email email) throws EmailException {
		email.setHostName(smtpHost);
		if (smtpUser != null && smtpPassword != null) {
			email.setAuthentication(smtpUser, smtpPassword);
		}

		if (smtpFromAddress != null) {
			email.setFrom(smtpFromAddress,smtpFromName);
		}
	}
}
